import ctypes
import json
import time

import pyautogui

windowLeft = 0
windowTop = 0
windowWidth = 0
windowHeight = 0

windowOffLeft = 300
windowOffTop = 100
windowOffRight = 540
windowOffBottom = 240

# 宽高3/4
walletWidth = 320
walletHeight = 480
walletCloseWidth = 40
walletCloseHeight = 40

walletUserInfoHeight = 100

openTime = 0
sendTextTime = 0
redis = None
bitType = 0
isSend = False

keyboardMap = {}





from utils import find_window_position_and_check_foreground, screenshot, getTextPosition, click, initRedis, send_text, \
    check, parseInfo, saveLotteryRecord


def find_window(window_title_keyword):
    global windowLeft, windowTop, windowWidth, windowHeight, redis
    windowInfo = find_window_position_and_check_foreground(window_title_keyword)
    windowLeft = windowInfo[0]
    windowTop = windowInfo[1]
    windowWidth = windowInfo[2]
    windowHeight = windowInfo[3]
    redis = initRedis()
    if windowLeft > 0:
        return True
    else:
        return False
def getCurrentSn():
    # 找到当前期的状态
    result = parseInfo(windowLeft, windowTop+200, 80,37,'getCurrentSn.png')
    try:
        return int(result[0])
    except Exception as e:
        return -1

def getCurrentSnStatus():
    # 找到当前期的状态
    #parseInfo(windowLeft, windowTop+200, 70,37)
    result = parseInfo(windowLeft+250, windowTop+200, 80,37,'getCurrentSnStatus.png')
    try:
        return result[0]
    except Exception as e:
        return "-1"

def openKeyboard():
    size = 40
    if "open" in keyboardMap:
        openPosition = keyboardMap["open"]
        click("open", openPosition[0], openPosition[1])
    else:
        screenshot(windowLeft+13, windowTop+windowHeight-50, size,size,"b")
        click("open",windowLeft+13+int(size/2),windowTop+windowHeight-50+int(size/2))
        keyboardMap["open"] = [windowLeft+13+int(size/2),windowTop+windowHeight-50+int(size/2)]

# 检查输入键盘是否打开
def check():
    check = getTextPosition("闲聊",windowLeft, windowTop, windowWidth, windowHeight)
    if check[0]>-1:
        return True
    else:
        print("输入键盘未打开，正在自动打开...")
        openKeyboard()
        check = getTextPosition("闲聊", windowLeft, windowTop, windowWidth, windowHeight)
        if check[0] > -1:
            return True
        else:
            print("[✘] 自动打开输入键盘失败，请手动打开")
            return False

def initKeyboard():
    findText('单')
    findText('双')
    findText('大')
    findText('小')
    findText('←')
    findText('/')
    for i in range(0, 10):
        findText(f'{i}')
    size = 40
    screenshot(
        windowLeft + windowWidth - 50,
        windowTop + int(windowHeight / 2) + 50,40,40,'send.png'
    )
    keyboardMap['send'] = [
        windowLeft + windowWidth-100 + int(100 / 2),
        windowTop + int(windowHeight / 2)-20+int(50/2)
    ]


def findText(text):
    top = 100
    #screenshot(windowLeft, windowTop + int(windowHeight / 2) + top, windowWidth, int(windowHeight / 2) - top, f'{text}')
    text1 = getTextPosition(f"{text}", windowLeft, windowTop + int(windowHeight / 2) + top, windowWidth,int(windowHeight / 2))
    if text1[0] > -1:
        keyboardMap[f'{text}'] = [windowLeft + text1[0] + int(text1[2] / 2), windowTop + int(windowHeight / 2) + top + text1[1] + int(text1[3] / 2)]
    else:
        print(f"未找到：{text}")
    if text=='3':
        keyboardMap['←'] = [windowLeft + text1[0]+60+int(100/2),windowTop + int(windowHeight / 2) + top + text1[1]-26+int(50/2)]
    return text1

def clickText(text):
    click(f"{text}",keyboardMap[f'{text}'][0],keyboardMap[f'{text}'][1])

def clear():
    for i in range(1,10):
        clickText("←")

def sendText(num,type,money):
    nums = list(num)
    types = list(type)
    moneys = list(money)
    for c in nums:
        clickText(f"{c}")
    clickText("/")
    for c in types:
        clickText(f"{c}")
    clickText("/")
    for c in moneys:
        clickText(f"{c}")
    #clickText("send")

def checkStatus():
    sn = getCurrentSn()
    status = getCurrentSnStatus()
    print(f"{sn}: {status}")
    if sn > -1 and (status == '' or status == '-1'):
        print("可以下注")
        return sn
    else:
        print("系统暂停下注")
        return -1

if __name__ == "__main__":
    # count = 0
    flag = find_window("名爵")
    text1 = getTextPosition("极速时时彩",windowLeft, windowTop, windowWidth, windowHeight)
    check()
    initKeyboard()
    redis = initRedis()
    while True:
        sn = checkStatus()
        data = redis.get("sendInfo") or "{}"
        json_str = json.loads(data)
        print(json_str)
        if sn >-1:
            num = int(json_str['num'] or '0')
            if num<=0:
                break
            type1 = json_str['type'] or '未知'
            betType = type1
            money = int(json_str['money'] or '0')
            send = int(json_str['send'] or '0')
            print(f'接口数据：数字:{num}:类型:{type1}:金额：{money}:是否已下注：{send}')
            if send==1:
                if 0 < num <= 5 and (type1 == '单' or type1 == '双' or type1 == '大' or type1 == '小'):
                    print("暂停10秒下注")
                    time.sleep(10)
                    clear()
                    if int(money)>0:
                        sendText(f"{num}", type1, f"{money}")
                    else:
                        print(f"金额是{money},不下注")
                    json_str['send'] = 0
                    redis.set("sendInfo", json.dumps(json_str))
                    saveLotteryRecord(type1,betType,10036,money,num,json_str['sn'])
                else:
                    print("不需要押注")
        time.sleep(5)








